<template>
  <div>
    <!-- 顶部视频播放器区域 -->
    <v-container fluid class="pb-0 px-2">
      <!-- 消息提示 -->
      <v-snackbar v-model="snackbar.show" :color="snackbar.color" :timeout="2000" location="top">
        {{ snackbar.text }}
      </v-snackbar>

      <!-- 主内容区域 - 使用两栏布局 -->
      <v-row>
        <!-- 左侧内容区域 -->
        <v-col :cols="colsWidth" class="pr-2">
          <!-- 视频播放器 -->
          <div class="video-player-container">
            <PlayerVideo
              v-if="videoData != null"
              :article="parseInt(id)"
              :video="videoData.video[0]"
              :picurl="videoData.imgUrl"
            />
          </div>

          <!-- 视频标题、分类和数据 -->
          <div v-if="videoData != null" class="video-info-container">
            <!-- 视频标题和标签信息 -->
            <h1 class="text-h5 font-weight-bold mb-2">{{ videoData.title }}</h1>
            
            <!-- 视频数据统计 -->
            <div class="d-flex align-center text-body-2 text-grey mb-3">
              <span>{{ TimeUtil.renderTime(videoData.createTime) }}</span>
              <v-divider vertical class="mx-2" style="height: 12px;"></v-divider>
              <span>{{ videoData.viewCount }} 播放</span>
              <v-divider vertical class="mx-2" style="height: 12px;"></v-divider>
              <span>{{ videoData.danmakuCount }} 弹幕</span>
              
              <v-spacer></v-spacer>
              
              <!-- 分类导航 -->
              <v-chip
                size="small"
                variant="flat"
                color="grey-lighten-3"
                class="mr-2"
                density="comfortable"
              >
                <router-link
                  v-if="videoData.childrenCategory.fatherId !== 0"
                  :to="`/v/${videoData.fatherCategory.id}`"
                  class="text-decoration-none text-caption"
                >
                  {{ videoData.fatherCategory.name }}
                </router-link>
                /
                <router-link
                  :to="`/v/${videoData.childrenCategory.id}`"
                  class="text-decoration-none text-caption"
                >
                  {{ videoData.childrenCategory.name }}
                </router-link>
              </v-chip>
            </div>

            <!-- 视频互动工具栏 -->
            <v-card variant="outlined" rounded="lg" class="mb-4">
              <v-row no-gutters>
                <!-- 左侧：UP主信息 -->
                <v-col cols="auto" class="pa-4 d-flex align-center">
                  <router-link :to="`/user/${videoData.userId}`">
                    <v-avatar size="48" class="mr-3">
                      <v-img :src="videoData.avatarUrl" alt="用户头像"></v-img>
                    </v-avatar>
                  </router-link>
                  
                  <div>
                    <router-link :to="`/user/${videoData.userId}`" class="text-decoration-none">
                      <div class="font-weight-bold">{{ videoData.username }}</div>
                    </router-link>
                    <div class="text-caption text-grey-darken-1 text-truncate">{{ videoData.introduction || "这个UP主还没有介绍自己" }}</div>
                  </div>
                  
                  <v-btn color="primary" variant="flat" rounded="lg" density="comfortable" class="ml-4">
                    <v-icon size="small" class="mr-1">mdi-plus</v-icon>
                    关注
                  </v-btn>
                </v-col>
                
                <v-divider vertical></v-divider>
                
                <!-- 右侧：互动按钮 -->
                <v-col class="pa-3 d-flex align-center">
                  <v-btn
                    prepend-icon="mdi-thumb-up"
                    :color="isLiked ? 'primary' : ''"
                    :variant="isLiked ? 'flat' : 'text'"
                    class="mr-1"
                    @click="likeVideo"
                  >
                    {{ videoData.likeCount }}
                  </v-btn>
                  
                  <v-btn
                    prepend-icon="mdi-thumb-down"
                    :color="isDisliked ? 'error' : ''"
                    :variant="isDisliked ? 'flat' : 'text'"
                    class="mr-1"
                    @click="dislikeVideo"
                  >
                    {{ videoData.dislikeCount }}
                  </v-btn>
                  
                  <v-btn
                    prepend-icon="mdi-coin"
                    variant="text"
                    class="mr-1"
                  >
                    投币
                  </v-btn>
                  
                  <v-btn
                    prepend-icon="mdi-content-save"
                    :color="isFavorited ? 'amber' : ''"
                    :variant="isFavorited ? 'flat' : 'text'"
                    class="mr-1"
                    @click="favoritesClick"
                  >
                    {{ isFavorited ? '已收藏' : '收藏' }}
                  </v-btn>
                  
                  <v-btn
                    prepend-icon="mdi-share-variant"
                    variant="text"
                    class="mr-1"
                  >
                    分享
                  </v-btn>
                </v-col>
              </v-row>
            </v-card>
            
            <!-- 视频描述 -->
            <v-card variant="outlined" rounded="lg" class="mb-4 px-4 py-3">
              <div class="text-body-1 mb-2">{{ videoData.describes }}</div>
              
              <!-- 标签 -->
              <div v-if="videoData.tag && videoData.tag.length > 0" class="mt-3">
                <v-chip-group>
                  <v-chip
                    v-for="item in videoData.tag"
                    :key="item"
                    size="small"
                    variant="flat"
                    color="primary-lighten-4"
                    class="mr-1"
                  >
                    {{ item }}
                  </v-chip>
                </v-chip-group>
              </div>
            </v-card>

            <!-- 评论区 - B站风格 -->
            <div class="comment-section mb-4">
              <div class="d-flex align-center justify-space-between mb-3">
                <div class="text-h6 font-weight-bold">评论 {{ videoData.commentCount }}</div>
                <div class="d-flex align-center">
                  <v-btn variant="text" size="small" active-class="" class="mr-1">
                    <span :class="commentSort === 'hot' ? 'text-primary font-weight-bold' : ''" @click="setCommentSort('hot')">热度</span>
                  </v-btn>
                  <v-divider vertical class="mx-1" style="height: 12px;"></v-divider>
                  <v-btn variant="text" size="small" active-class="">
                    <span :class="commentSort === 'time' ? 'text-primary font-weight-bold' : ''" @click="setCommentSort('time')">时间</span>
                  </v-btn>
                </div>
              </div>
              
              <!-- 评论输入框 -->
              <v-card variant="outlined" rounded="lg" class="mb-4 bilibili-comment-input">
                <div class="d-flex pa-3">
                  <v-avatar size="40" class="mr-3">
                    <v-img :src="userInfo.userData ? userInfo.userData.avatarUrl : '/favicon.png'" alt="用户头像"></v-img>
                  </v-avatar>
                  <div class="flex-grow-1">
                    <v-textarea
                      v-model="commentText"
                      rows="1"
                      auto-grow
                      variant="outlined"
                      density="comfortable"
                      hide-details
                      placeholder="发一条友善的评论"
                      class="comment-textarea"
                      :disabled="!userInfo.userData"
                    ></v-textarea>
                  </div>
                </div>
                <div class="d-flex justify-space-between px-3 pb-3">
                  <div class="d-flex align-center">
                    <v-btn icon="mdi-emoticon-outline" variant="text" size="small" class="mr-1"></v-btn>
                    <v-btn icon="mdi-image-outline" variant="text" size="small" class="mr-1"></v-btn>
                    <v-btn icon="mdi-at" variant="text" size="small"></v-btn>
                  </div>
                  <v-btn 
                    color="primary" 
                    rounded="lg"
                    :disabled="!userInfo.userData || !commentText.trim()"
                    @click="submitComment"
                  >
                    发布
                  </v-btn>
                </div>
              </v-card>
              
              <!-- 评论列表 -->
              <Comment
                :article="id"
                :author-id="videoData.userId"
                :typenum="1"
                :count="videoData.commentCount"
              />
            </div>
          </div>
        </v-col>

        <!-- 右侧推荐视频区域 -->
        <v-col v-if="colsWidth === 8" cols="4" class="pl-0">
          <v-card class="mb-4 overflow-hidden" flat>
            <div class="d-flex align-center justify-space-between px-3 py-3">
              <div class="text-subtitle-1 font-weight-bold">相关推荐</div>
              <v-btn 
                variant="text" 
                density="comfortable" 
                color="primary"
                size="small"
              >
                <v-icon size="small" class="mr-1">mdi-refresh</v-icon>
                换一换
              </v-btn>
            </div>
            
            <!-- 推荐视频列表 -->
            <div class="recommendation-container">
              <div 
                v-for="i in showRecommendations ? 12 : 6" 
                :key="i" 
                class="recommendation-item d-flex px-3 py-2"
                :class="i !== (showRecommendations ? 12 : 6) ? 'border-b' : ''"
              >
                <div class="recommendation-thumbnail mr-2 position-relative">
                  <v-responsive :aspect-ratio="16/9" width="160" class="rounded-sm overflow-hidden">
                    <v-skeleton-loader type="image" height="90"></v-skeleton-loader>
                  </v-responsive>
                  <div class="video-duration">{{ Math.floor(Math.random() * 10) + 1 }}:{{ Math.floor(Math.random() * 60).toString().padStart(2, '0') }}</div>
                </div>
                
                <div class="recommendation-info flex-grow-1">
                  <div class="recommendation-title text-subtitle-2 font-weight-medium text-truncate-2">
                    <v-skeleton-loader type="text" width="100%"></v-skeleton-loader>
                  </div>
                  
                  <div class="recommendation-uploader mt-1 d-flex align-center">
                    <span class="text-caption text-grey">
                      <v-skeleton-loader type="text" width="60%"></v-skeleton-loader>
                    </span>
                  </div>
                  
                  <div class="recommendation-stats d-flex align-center mt-1">
                    <span class="text-caption text-grey mr-2">
                      <v-skeleton-loader type="text" width="40%"></v-skeleton-loader>
                    </span>
                  </div>
                </div>
              </div>
              
              <!-- 展开/收起按钮 -->
              <div class="d-flex justify-center py-2 border-t">
                <v-btn
                  variant="text"
                  color="primary"
                  density="comfortable"
                  @click="toggleRecommendations"
                >
                  {{ showRecommendations ? '收起' : '展开更多' }}
                  <v-icon size="small" class="ml-1">{{ showRecommendations ? 'mdi-chevron-up' : 'mdi-chevron-down' }}</v-icon>
                </v-btn>
              </div>
            </div>
          </v-card>
        </v-col>
      </v-row>
    </v-container>
  </div>
</template>

<script>
import TimeUtil from '@/utils/time-util.vue'
import PlayerVideo from '@/components/player/PlayerVideo.vue'
import Comment from '@/views/comment/VideoComment.vue'
import { useUserStore } from '@/stores/userStore'
export default {
  name: 'VideoView',
  components: {
    PlayerVideo,
    Comment,
  },
  data() {
    return {
      score: 0,
      TimeUtil,
      id: 0,
      videoData: null,
      windowSize: {},
      colsWidth: 8,
      isLiked: false,
      isDisliked: false,
      isFavorited: false,
      userInfo: useUserStore(),
      snackbar: {
        show: false,
        text: '',
        color: 'success',
      },
      commentText: '',
      commentSort: 'hot',
      showRecommendations: false
    }
  },
  created() {
    window.scrollTo({
      top: 0,
      behavior: 'smooth',
    })
    this.id = parseInt(this.$route.params.id)
    this.videoInfo()
    this.onResize()
    window.addEventListener('resize', this.onResize)
  },
  beforeUnmount() {
    window.removeEventListener('resize', this.onResize)
  },
  methods: {
    // 控制页面大小
    onResize() {
      this.windowSize = { x: window.innerWidth, y: window.innerHeight }
      if (this.windowSize.x < 900) {
        this.colsWidth = 12
      } else {
        this.colsWidth = 8
      }
    },
    videoInfo() {
      this.httpGet(`/article/video/${this.id}`, (json) => {
        if (json.status === 200 && json.data.isShow) {
          this.videoData = json.data
          document.title = json.data.title
          // 假设数据中包含点赞和点踩数量，如果没有则使用默认值
          this.likeCount = json.data.likeCount || 0
          this.dislikeCount = json.data.dislikeCount || 0
          this.checkLike()
          this.checkFavorites()
        } else {
          // TODO 显示 404
          this.$router.push('/')
        }
      })
    },
    // 点赞功能
    likeVideo() {
      // 如果用户未登录
      if (this.userInfo.userData == null) {
        this.showMessage('请先登录后再点赞', 'warning')
        return
      }
      this.httpPost(`/like/toggle?likeObjId=${this.id}&type=0`, {}, (json) => {
        if (json.status === 200) {
          // 更新点赞状态
          this.isLiked = json.data.like
          // 更新点赞数量
          this.videoData.likeCount += json.data.like ? 1 : -1
          // 显示消息提示
          this.showMessage(json.data.info, 'success')
        } else {
          this.showMessage(json.data.info || '操作失败', 'error')
        }
      })
    },
    favoritesClick() {
      if (this.userInfo.userData == null) {
        this.showMessage('请先登录后再收藏', 'warning')
        return
      }
      this.httpPost('/favorites/toggle', { articeId: this.id }, (json) => {
        if (json.data.id != null) {
          this.showMessage('收藏成功！', 'success')
          this.isFavorited = true
          this.videoData.favoriteCount += 1
        } else {
          this.showMessage('取消收藏成功！', 'info')
          this.isFavorited = false
          this.videoData.favoriteCount -= 1
        }
      })
    },
    checkFavorites() {
      if (this.userInfo.userData == null) {
        this.isFavorited = false
        return
      }
      this.httpGet(`/favorites/check?articleId=${this.id}`, (json) => {
        if (json.status === 200) {
          this.isFavorited = json.data
        }
      })
    },
    checkLike() {
      if (this.userInfo.userData == null) {
        this.isLiked = false
        return
      }
      this.httpGet(`/like/status?likeObjId=${this.id}&type=0`, (json) => {
        if (json.status === 200) {
          this.isLiked = json.data
        }
      })
    },
    // 点踩功能
    dislikeVideo() {
      // TODO 待实现
      this.showMessage('点踩功能暂未实现', 'info')
    },
    // 显示消息提示
    showMessage(text, color = 'success') {
      this.snackbar.text = text
      this.snackbar.color = color
      this.snackbar.show = true
    },
    // 设置评论排序方式
    setCommentSort(sort) {
      this.commentSort = sort
      // 这里可以添加实际的排序逻辑
    },
    // 提交评论
    submitComment() {
      if (!this.userInfo.userData) {
        this.showMessage('请先登录后再评论', 'warning')
        return
      }
      if (!this.commentText.trim()) {
        this.showMessage('评论内容不能为空', 'warning')
        return
      }
      
      // 这里可以添加实际的提交评论逻辑
      this.showMessage('评论发布成功', 'success')
      this.commentText = ''
    },
    // 切换推荐视频展开/收起状态
    toggleRecommendations() {
      this.showRecommendations = !this.showRecommendations
    }
  },
}
</script>

<style>
.category-link {
  color: #1867c0;
}
.border-b {
  border-bottom: 1px solid rgba(0, 0, 0, 0.12);
}
.border-t {
  border-top: 1px solid rgba(0, 0, 0, 0.12);
}
.text-truncate-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}
.recommendation-item {
  transition: background-color 0.2s;
}
.recommendation-item:hover {
  background-color: rgba(0, 0, 0, 0.03);
  cursor: pointer;
}
.video-duration {
  position: absolute;
  bottom: 4px;
  right: 4px;
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 0 4px;
  border-radius: 2px;
  font-size: 12px;
}

/* 评论区样式 */
.comment-textarea .v-field__field {
  padding-top: 6px !important;
}
.bilibili-comment-input .v-field__outline {
  opacity: 0.4;
}
.bilibili-comment-input .v-field--focused .v-field__outline {
  opacity: 1;
}

/* 视频播放器样式 */
.video-player-container {
  width: 100%;
  margin-bottom: 16px;
}

/* 大屏幕设备的响应式尺寸 */
@media (min-width: 1600px) {
  .video-player-container {
    max-width: 1280px;
    margin: 0 auto 16px;
  }
  
  .video-info-container {
    max-width: 1280px;
    margin: 0 auto;
  }
}

/* 超大屏幕设备 */
@media (min-width: 1920px) {
  .video-player-container {
    max-width: 1600px;
  }
  
  .video-info-container {
    max-width: 1600px;
  }
}

/* 推荐视频容器 */
.recommendation-container {
  max-height: 100%;
  overflow: hidden;
}
</style>